package com.jxl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jxl.entity.dto.RoutDTO;
import com.jxl.entity.dto.RouteStationDTO;
import com.jxl.entity.po.Route;
import com.jxl.entity.po.RouteStation;
import com.jxl.entity.po.Schedule;
import com.jxl.entity.query.RoutePageQuery;
import com.jxl.entity.vo.PageResponse;
import com.jxl.entity.vo.UserVO;
import com.jxl.mapper.RouteMapper;
import com.jxl.mapper.RouteStationMapper;
import com.jxl.service.IRouteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxl.service.IRouteStationService;
import com.jxl.service.IScheduleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 线路表 服务实现类
 * </p>
 *
 * @author 金小梁
 * @since 2025-06-08
 */
@Service
public class RouteServiceImpl extends ServiceImpl<RouteMapper, Route> implements IRouteService {
    @Autowired
    private IRouteStationService routeStationService;
    @Autowired
    private RouteMapper routeMapper;
    @Autowired
    private RouteStationMapper routeStationMapper;
    @Autowired
    private IScheduleService scheduleService;



    /**
     * 新增路线
     *
     * @param routDTO
     */
    @Override
    public void addRoute(RoutDTO routDTO) {
        //查询是否有编号相同的线路
        List<Route> list = query().eq("route_no", routDTO.getRouteNo()).list();
        if(list.size()>0){
            throw new RuntimeException("该线路编号已存在");
        }
        Route route = new Route();
        //拷贝属性
        BeanUtil.copyProperties(routDTO, route);
        //保存并返回主键id
        save(route);
        routDTO.setId(route.getId());
        //保存线路站点关联信息
        List<RouteStation> routeStations = new ArrayList<>();
        //将站点信息保存到集合中
        for (RouteStationDTO routeStationDTO : routDTO.getRouteStations()) {
            RouteStation routeStation = new RouteStation();
            BeanUtil.copyProperties(routeStationDTO,routeStation);
            routeStation.setRouteId(routDTO.getId());
            routeStations.add(routeStation);
        }
        //批量保存中间表
        routeStationService.saveBatch(routeStations);
    }

    /**
     * 分页查询
     *
     * @param routePageQuery
     * @return
     */
    @Override
    public PageResponse<RoutDTO> queryRoutes(RoutePageQuery routePageQuery) {
        PageHelper.startPage(routePageQuery.getPageNum(),  routePageQuery.getPageSize());
        Page<RoutDTO> routDTOPage = routeMapper.selectByPageQuery(routePageQuery);
        List<RoutDTO> records = routDTOPage.getResult();
        //循环遍历，查询出每个线路的站点信息
        records.forEach(routDTO -> {
            List<RouteStationDTO> routeStationDTOS =routeStationMapper.selectByRouteId(routDTO.getId());
            routDTO.setRouteStations(routeStationDTOS);
        });
        PageResponse<RoutDTO> pageResponse = PageResponse.of(routDTOPage,  RoutDTO.class);
        return pageResponse;
    }


    /**
     * 删除
     *
     * @param ids
     */
    @Override
    public void deleteByIds(List<Long> ids) {
        //查询该线路是否被排班
        List<Route> routeList = query().in("id", ids).list();
        routeList.forEach(route -> {
            List<Schedule> list = scheduleService.query().eq("route_no", route.getRouteNo()).list();
            if(list.size()>0){
                throw new RuntimeException("该线路正在被排班，请先取消排班");
            }
        });
        //删除所有的线路
        removeByIds(ids);
        //删除所有的线路站点关联信息
        routeStationMapper.deleteByRouteIds(ids);
    }

    /**
     * 修改
     *
     * @param routDTO
     */
    @Override
    @Transactional
    public void updateRoute(RoutDTO routDTO) {
        //删除线路站点关联信息
        routeStationService.remove(new QueryWrapper<RouteStation>().eq("route_id", routDTO.getId()));
        //查询是否有编号相同的线路
        List<Route> list = query().eq("route_no", routDTO.getRouteNo()).ne("id", routDTO.getId()).list();
        if(list.size()>0){
            throw new RuntimeException("该线路编号已存在");
        }
        Route route = new Route();
        //拷贝属性
        BeanUtil.copyProperties(routDTO, route);
        route.setUpdateTime(LocalDateTime.now());
        //更新并返回主键id
        updateById(route);
        routDTO.setId(route.getId());
        //保存线路站点关联信息
        List<RouteStation> routeStations = new ArrayList<>();
        //将站点信息保存到集合中
        for (RouteStationDTO routeStationDTO : routDTO.getRouteStations()) {
            RouteStation routeStation = new RouteStation();
            BeanUtil.copyProperties(routeStationDTO,routeStation);
            routeStation.setRouteId(routDTO.getId());
            routeStations.add(routeStation);
        }
        //批量保存中间表
        routeStationService.saveBatch(routeStations);
    }
}
